package liuru.world.observation.controller;

import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Timer;
import liuru.world.observation.controller.constant.MetricConstants;
import liuru.world.observation.controller.observability.metric.FileTotalGauge;
import liuru.world.observation.controller.observability.metric.ScheduleTaskCounter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("micrometer")
public class TestObservationController {
    @Autowired
    private FileTotalGauge fileTotalGauge;
    @Autowired
    private ScheduleTaskCounter scheduleTaskCounter;
    @GetMapping("testTimer")
    public String testTimer(){
        Timer timer = Metrics.timer("http_testTimer_duration","url","/micrometer/testTimer");
        timer.record(() -> {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        return "testTimer";
    }
    @GetMapping("testCounter")
    public String testCounter(){
        Counter counter = Metrics.counter("http_testCounter_total","url","/micrometer/testCounter");
        counter.increment();
        return "testCounter";
    }
    @GetMapping("testGauge")
    public String testGauge(){
        fileTotalGauge.addFileCount(MetricConstants.DELETED,3);
        fileTotalGauge.subtractFileCount(MetricConstants.DELETED,2);
        fileTotalGauge.addFileCount(MetricConstants.TEMPORARY,10);
        fileTotalGauge.subtractFileCount(MetricConstants.TEMPORARY,8);
        fileTotalGauge.addFileCount(MetricConstants.PERMANENT,12);
        fileTotalGauge.subtractFileCount(MetricConstants.PERMANENT,9);
        scheduleTaskCounter.increment(MetricConstants.CLEANUP,MetricConstants.TOTAL);
        scheduleTaskCounter.increment(MetricConstants.CLEANUP,MetricConstants.SUCCESS);
        scheduleTaskCounter.increment(MetricConstants.DELETE_FILE,MetricConstants.TOTAL);
        scheduleTaskCounter.increment(MetricConstants.DELETE_FILE,MetricConstants.SUCCESS);
        return "testGauge";
    }
}
